package com.javabaas.server.novel_server.redis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.concurrent.TimeUnit;

@Service
public class RedisService {

    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 删除指定key的value
     * @param key redis key
     */
    public void delete(String key) {
        if (exists(key)) {
            redisTemplate.delete(key);
        }
    }


    /**
     * 判断缓存中是否有对应的key
     * @param key redis key
     * @return boolean
     */
    public boolean exists(String key) {
        return redisTemplate.hasKey(key);
    }


    /**
     * 读取缓存
     *
     * @param key redis key
     */
    public Object get(String key) {
        ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
        return operations.get(key);
    }


    /**
     * 写入缓存
     *
     * @param key redis key
     *
     * @param value redis value
     */
    public boolean set(String key, Object value) {
        boolean flag = false;
        ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
        operations.set(key, value);
        flag = true;
        return flag;
    }


    /**
     * 写入缓存
     *
     * @param key redis key
     *
     * @param value redis value
     *
     * @param expireTime 过期时间 (seconds)
     */
    public boolean set(String key, Object value, long expireTime) {
        boolean flag = false;
        ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
        operations.set(key, value);
        redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
        flag = true;
        return flag;
    }
}
